<?php

namespace plugin\admin\app\controller;

use app\services\RequestService;
use plugin\admin\app\model\PriceLog;
use plugin\admin\app\model\VipOrder;
use support\Db;
use support\Request;
use support\Response;
use plugin\admin\app\model\NetworkOrder;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 网络订单 
 */
class NetworkOrderController extends Crud
{
    
    /**
     * @var NetworkOrder
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new NetworkOrder;
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order)->whereNotNull('orderDateTime')->where(function ($q){
            $q->whereNull('state')->orWhere('state', '!=', 3);
        })->orderBy('is_reward','desc');
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order= 'desc')
    {
        $model = $this->model;
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                }elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function doFormat($query, $format, $limit): Response
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];;
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        $total_price = PriceLog::where('appid','90F4F7FC5562A459D98F1C6B0FB82CF6')->value('price')??0;
        $total_price = RequestService::priceFormat($total_price);
        $reward_order = NetworkOrder::where(['is_reward'=>0,'is_record'=>1,'appid'=>'90F4F7FC5562A459D98F1C6B0FB82CF6'])->whereNotNull('customerNumber')->whereNotNull('reward_total_price')->where(function ($q){
            $q->whereNull('state')->orWhere('state','!=',3);
        })->orderBy('id')->first();
        foreach ($items as $k => $v){
            $price = RequestService::priceFormat($v['reward_total_price']);
            if (!empty($reward_order) && $v['id']==$reward_order['id']){
                $items[$k]['progress'] = bcdiv($total_price,$price, 2)*100 . '%';
            }
            if ($v['is_reward'] == 1){
                $items[$k]['progress'] = '100%';
            }
        }
        if (method_exists($this, "afterQuery")) {
            $items = call_user_func([$this, "afterQuery"], $items);
        }
        $format_function = $methods[$format] ?? 'formatNormal';
        return call_user_func([$this, $format_function], $items, $total,['total_price'=>number_format($total_price, 2)]);
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('network-order/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('network-order/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('network-order/update');
    }

    // 跳转订单商品页面
    public function itemsInfo(Request $request)
    {
        return view('network-order/items');

    }

    // 订单商品数据
    public function itemsInfo1(Request $request)
    {
        $data = NetworkOrder::where('id', $request->get('id'))->first();
        if (!empty($data)){
            $data = $data->toArray();
            foreach ($data['items'] as $k => $v){
                if (!isset($v['is_reward'])){
                    $data['items'][$k]['is_reward'] = 1;
                }
                $price = $v['productSellPrice']??$v['sellPrice'];
                $data['items'][$k]['productSellPrice'] = number_format($price, 2);
                $number = $v['productQuantity']??$v['quantity'];
                $data['items'][$k]['productQuantity'] = $number;
                $data['items'][$k]['productName'] = $v['productName']??$v['name'];
            }
            return $this->json(0, 'success', $data['items']);
        }
        return $this->json(1, '数据不存在');

    }

    public static function getOrderData($appId = '90F4F7FC5562A459D98F1C6B0FB82CF6')
    {
        $network_orders = NetworkOrder::select(Db::raw('
            COUNT(*) as order_num, 
            SUM(totalAmount) as order_total_price, 
            SUM(CASE WHEN is_reward = 1 THEN 1 ELSE 0 END) as free_order_num, 
            SUM(CASE WHEN is_reward = 0 THEN 1 ELSE 0 END) as no_free_order_num, 
            SUM(CASE WHEN reward_total_price != 0.00 THEN 1 ELSE 0 END) as reward_order_num, 
            SUM(CASE WHEN is_reward = 1 THEN reward_total_price ELSE 0 END) as total_reward
        '))
            ->where('appid', $appId)
            ->first();

        // 待发放奖励订单
        $reward_order = NetworkOrder::where([
            'is_reward' => 0,
            'is_record' => 1,
            'appid' => $appId
        ])
            ->whereNotNull('customerNumber')
            ->whereNotNull('reward_total_price')
            ->where(function ($q) {
                $q->whereNull('state')->orWhere('state', '!=', 3);
            })
            ->orderBy('id')
            ->first();

        // 资金池金额
        $total_price = PriceLog::where('appid', $appId)->value('price') ?? 0;

        $result = [
            'order_num' => $network_orders->order_num, // 消费订单
            'order_total_price' => $network_orders->order_total_price, // 销售总额
            'free_order_num' => $network_orders->free_order_num, // 互助订单
            'no_free_order_num' => $network_orders->no_free_order_num, // 排队订单
            'reward_order_num' => $network_orders->reward_order_num, //
            'total_reward' => $network_orders->total_reward, // 已互助金额
            'reward_order' => $reward_order, // 待发放奖励订单
            'total_price' => $total_price, // 资金池金额
        ];

        // 计算订单进度，处理除以0的情况
        $result['progress'] = $result['order_num'] > 0 ? bcdiv($result['free_order_num'], $result['order_num'], 2) * 100 . '%' : '0%';

        return $result;
    }


}
